﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;

namespace SpeedOctopusNet.Service.Transmission;

/// <summary>
/// 通用MQTT客户端
/// </summary>
public abstract class MqttClientHostedService : BackgroundService
{
    /// <summary>
    /// 待发送列表
    /// </summary>
    private readonly BlockingCollection<SendItem> _sendList = new();

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="logger">logger</param>
    /// <param name="messageProxy">消息代理程序</param>
    /// <param name="clientParams">客户端参数</param>
    public MqttClientHostedService(ILogger<MqttClientHostedService> logger)
    {
        Task.Factory.StartNew(state => OnSendMsg(), this, TaskCreationOptions.LongRunning);
    }

    /// <summary>
    /// 启动服务
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public override async Task StartAsync(CancellationToken cancellationToken)
    {
        //await Connect(cancellationToken);

        await base.StartAsync(cancellationToken);
    }

    /// <summary>
    /// 停止服务
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        //await DisConnect(cancellationToken);
        //_sendList.CompleteAdding();

        await base.StopAsync(cancellationToken);
    }

    /// <summary>
    /// 处理队列，依次推送
    /// </summary>
    private async void OnSendMsg()
    {
        foreach (var sendItem in _sendList.GetConsumingEnumerable())
        {
            await Task.CompletedTask;
        }
    }

    /// <summary>
    /// 重新连接
    /// </summary>
    private async Task<bool> Connect(CancellationToken cancellationToken)
    {
        return await Task.FromResult(true);
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    private async Task DisConnect(CancellationToken cancellationToken)
    {
        await Task.CompletedTask;
    }


    protected abstract void SubscribeTopics();

    /// <summary>
    /// 执行任务（不需要实现）
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    protected sealed override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await Task.CompletedTask;
    }
}
